import Taro from "@tarojs/taro";
import { makeAutoObservable } from "mobx";
import { request } from "@/services/httpRequest";

type UserInfo = {
  "id": number,
  "nickname": string,
  "avatarUrl"?: string,
}

type RegisterUser = {
  "nickname": string,
  "avatarUrl"?: string,
}

/**
 * 身份相关信息-全局
 */
export class UserStore {
  constructor() {
    makeAutoObservable(this);
  }

  isLogin = false;

  userInfo: UserInfo = {
    id: 0,
    nickname: '',
    avatarUrl: '',
  };

  setUserInfo = (userInfo: UserInfo) => {
    this.userInfo = { ...userInfo };
  }

  setIsLogin = (isLogin: boolean) => {
    this.isLogin = isLogin;
  }

  handleLogin = async () => {
    Taro.showLoading({
      title: '登录中...',
    });
    try {
      const codeRes = await Taro.login();
      if (codeRes.code) {
        // 获取登录凭证（code），你可以在这里通过调用自己的后端接口，拿到 session_key 等信息
        console.log('微信登录成功，code:', codeRes.code);
        const res = await request({
          url: '/api/user/login',
          method: 'POST',
          data: {
            code: codeRes.code,
          },
        });
        Taro.hideLoading();
        if (res.code === 200) {
          Taro.showToast({
            title: '登录成功',
            icon: 'success',
          });
          // 登录成功，保存用户信息
          Taro.setStorageSync('userInfo', res.data);
          this.setUserInfo(res.data);
          this.setIsLogin(true);
          // 跳转到主页
          setTimeout(() => {
            Taro.switchTab({
              url: '/pages/index/index',
            });
          }, 1500);

        } else if (res.code === 1) {
          // 未注册
          Taro.showModal({
            title: '请先注册',
            content: '该操作不会主动获取您的个人信息，请放心使用',
            success: (res) => {
              if (res.confirm) {
                // 用户点击确定，跳转到注册页面
                Taro.navigateTo({
                  url: `/pages/profile-edit/index`,

                });
              } else if (res.cancel) {
                // 用户点击取消，不做任何操作
              }
            }
          })
        }

      }
      Taro.hideLoading();
    } catch (error) {
      Taro.showToast({
        title: '登录异常',
        icon: 'none',
      });
    }

  }

  handleRegister = async (userInfo: RegisterUser) => {
    const { nickname, avatarUrl } = userInfo;

    try {
      const res = await request({
        url: '/api/user/register',
        method: 'POST',
        data: {
          nickname,
          avatarUrl,
        },
      });
      console.log(res, '注册成功');

      Taro.showToast({
        title: '注册成功',
        icon: 'success',
      });
      this.setIsLogin(true); // 注册成功，保存用户信息
      Taro.setStorageSync('userInfo', res.data);
      // 跳转到主页
      this.handleLogin()

    } catch (error) {
      Taro.showToast({
        title: '注册失败',
        icon: 'none',
      });
    }
  }

  onLayOut = () => {
    Taro.showModal({
      title: '提示',
      content: '确定退出登录？',
      success: (res) => {
        if (res.confirm) {
          this.logOut();
        }
      }
    })
  }

  logOut = () => {
    Taro.showLoading({
      title: '正在退出...',
    })
    setTimeout(() => {
      this.setIsLogin(false);
      this.setUserInfo({
        id: 0,
        nickname: '',
        avatarUrl: '',
      });
      Taro.removeStorageSync('token');
      Taro.hideLoading();
      Taro.navigateTo({
        url: '/pages/login/index',
      })

    }, 1000);

  }

  requestUserInfo = async () => {
    try {
      const res = await request({
        url: '/api/user',
        method: 'GET',
      });

      this.setUserInfo(res.data);
      this.setIsLogin(true);
      console.log(res, 'res');
    } catch (error) {

      Taro.showModal({
        title: '提示',
        content: '获取用户信息失败，是否重新登录',
        success: (res) => {
          if (res.confirm) {
            Taro.reLaunch({
              url: '/pages/login/index',
            })
          }
        }
      })
      console.log(error, 'error');
    }
  }



}

export const userStore = new UserStore();
